const pool = require('../config/db');

// 定义与数据库枚举匹配的订单类型（小写）
const VALID_ORDER_TYPES = {
  DINE_IN: 'dine_in',       // 匹配数据库的dine_in
  DELIVERY: 'delivery'      // 匹配数据库的delivery
};

// 生成订单号
const generateOrderNo = () => {
  const timestamp = new Date().getTime();
  const random = Math.random().toString(36).substr(2, 9).toUpperCase();
  return `ORD${timestamp}${random}`;
};

// 辅助函数：处理 undefined 值为 null
const safeValue = (value) => {
  return value === undefined ? null : value;
};

// 安全处理 JSON 序列化
const safeJSONStringify = (obj) => {
  try {
    return obj ? JSON.stringify(obj) : '{}';
  } catch (error) {
    console.error('JSON 序列化失败:', error);
    return '{}';
  }
};

// 安全处理 JSON 解析
const safeJSONParse = (str) => {
  if (!str) return {};
  
  try {
    if (typeof str === 'object') return str;
    if (typeof str === 'string' && (str.startsWith('{') || str.startsWith('['))) {
      return JSON.parse(str);
    }
    return {};
  } catch (error) {
    console.error('JSON 解析失败:', error, '原始值:', str);
    return {};
  }
};

// 验证并标准化订单类型（转换为数据库需要的小写格式）
const validateOrderType = (orderType) => {
  if (!orderType) {
    console.warn('未指定订单类型，默认使用堂食');
    return VALID_ORDER_TYPES.DINE_IN;
  }
  
  // 转换为小写并去除空格，确保与数据库枚举匹配
  const normalizedType = orderType.trim().toLowerCase();
  
  if (Object.values(VALID_ORDER_TYPES).includes(normalizedType)) {
    return normalizedType;
  }
  
  console.warn(`无效的订单类型: ${orderType}，已自动转换为默认值`);
  return VALID_ORDER_TYPES.DINE_IN;
};

// 创建订单（使用 mysql2）
exports.createOrder = async (req, res) => {
  let connection;
  try {
    console.log('🔍 创建订单请求开始');
    
    // 验证用户认证
    if (!req.user || !req.user.id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证，请重新登录'
      });
    }

    const user_id = req.user.id;
    const {
      shop_id,
      items,
      total_amount,
      discount_amount = 0,
      delivery_fee = 0,
      order_type,
      table_no,
      take_time,
      address_id,
      pay_type = 'wechat',
      remark
    } = req.body;

    // 验证必要参数
    if (!shop_id || !items || !total_amount) {
      return res.status(400).json({ 
        success: false,
        message: '店铺ID、商品列表和总金额不能为空' 
      });
    }

    if (!Array.isArray(items) || items.length === 0) {
      return res.status(400).json({ 
        success: false,
        message: '商品列表不能为空' 
      });
    }

    // 关键修复：标准化订单类型为数据库枚举格式
    const normalizedOrderType = validateOrderType(order_type);
    console.log('🔍 标准化后的订单类型:', normalizedOrderType);

   // 新增：验证外卖订单的地址信息
    if (normalizedOrderType === VALID_ORDER_TYPES.DELIVERY) {
      if (!address_id) {
        return res.status(400).json({
          success: false,
          message: '外卖订单必须提供收货地址'
        });
      }
      
      // 验证地址ID是否存在于用户的地址列表中
      const [addressResult] = await pool.execute(
        'SELECT id FROM addresses WHERE id = ? AND user_id = ?',
        [address_id, user_id]
      );
      
      if (addressResult.length === 0) {
        return res.status(400).json({
          success: false,
          message: '无效的收货地址，请选择正确的地址'
        });
      }
    }

    // 验证堂食订单的桌位信息
    if (normalizedOrderType === VALID_ORDER_TYPES.DINE_IN && !table_no) {
      return res.status(400).json({
        success: false,
        message: '堂食订单必须提供桌号信息'
      });
    }


    // 验证订单项
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (!item.dish_id || !item.dish_name || !item.actual_price || !item.quantity) {
        return res.status(400).json({
          success: false,
          message: `第${i + 1}个商品信息不完整`
        });
      }
    }

    // 数据库操作
    connection = await pool.getConnection();
    await connection.beginTransaction();

    const total = parseFloat(total_amount);
    const discount = parseFloat(discount_amount);
    const delivery = parseFloat(delivery_fee);
    const pay_amount = total - discount + delivery;
    const order_no = generateOrderNo();

    // 插入订单记录（使用标准化后的订单类型）
    const orderSql = `
      INSERT INTO orders (
        order_no, user_id, shop_id, total_amount, pay_amount, 
        discount_amount, delivery_fee, order_type, table_no, 
        take_time, address_id, pay_type, remark, status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    `;

    const [orderResult] = await connection.execute(orderSql, [
      order_no, 
      user_id, 
      shop_id, 
      total, 
      pay_amount, 
      discount, 
      delivery, 
      normalizedOrderType,  // 确保与数据库枚举匹配
      safeValue(table_no),
      safeValue(take_time), 
      safeValue(address_id), 
      pay_type, 
      safeValue(remark)
    ]);

    const order_id = orderResult.insertId;
    console.log('✅ 订单创建成功，订单ID:', order_id);

    // 插入订单项
    const orderItemSql = `
      INSERT INTO order_items (
        order_id, dish_id, dish_name, dish_image, original_price,
        actual_price, quantity, total_price, category_id, category_name, specifications
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    for (const item of items) {
      const total_price = parseFloat(item.actual_price) * parseInt(item.quantity);
      const specifications = safeJSONStringify(item.specifications);
      
      await connection.execute(orderItemSql, [
        order_id, 
        item.dish_id, 
        item.dish_name, 
        safeValue(item.dish_image),
        parseFloat(item.original_price), 
        parseFloat(item.actual_price),
        parseInt(item.quantity), 
        total_price, 
        safeValue(item.category_id),
        safeValue(item.category_name), 
        specifications
      ]);
    }

    await connection.commit();
    
    // 查询并返回完整订单信息
    const [orders] = await connection.execute(`SELECT * FROM orders WHERE id = ?`, [order_id]);
    const [orderItems] = await connection.execute(`SELECT * FROM order_items WHERE order_id = ?`, [order_id]);

    const processedItems = orderItems.map(item => ({
      ...item,
      specifications: safeJSONParse(item.specifications)
    }));

    res.status(201).json({
      success: true,
      message: '订单创建成功',
      data: { ...orders[0], items: processedItems }
    });

  } catch (error) {
    if (connection) await connection.rollback();
    console.error('❌ 创建订单失败:', error);
    res.status(500).json({ 
      success: false,
      message: '创建订单失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  } finally {
    if (connection) connection.release();
  }
};



// 获取用户订单列表（使用 mysql2）
exports.getUserOrders = async (req, res) => {
  let connection;
  try {
    if (!req.user || !req.user.id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    const user_id = req.user.id;
    console.log('🔍 获取用户订单，用户ID:', user_id);

    connection = await pool.getConnection();

    // 查询用户的所有订单
    const [orders] = await connection.execute(`
      SELECT * FROM orders 
      WHERE user_id = ? 
      ORDER BY created_at DESC
    `, [user_id]);

    // 为每个订单查询订单项
    const ordersWithItems = [];
    for (const order of orders) {
      const [orderItems] = await connection.execute(`
        SELECT * FROM order_items WHERE order_id = ?
      `, [order.id]);

      // 使用安全的 JSON 解析处理规格字段
      const processedItems = orderItems.map(item => ({
        ...item,
        specifications: safeJSONParse(item.specifications)
      }));

      ordersWithItems.push({
        ...order,
        items: processedItems
      });
    }

    res.json({
      success: true,
      message: '获取订单列表成功',
      data: ordersWithItems
    });

  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({ 
      success: false,
      message: '获取订单列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
};

// 获取订单详情（使用 mysql2）
exports.getOrderDetail = async (req, res) => {
  let connection;
  try {
    const { order_id } = req.params;
    console.log('🔍 获取订单详情，订单ID:', order_id);

    connection = await pool.getConnection();

    // 查询订单
    const [orders] = await connection.execute(`
      SELECT * FROM orders WHERE id = ?
    `, [order_id]);

    if (orders.length === 0) {
      return res.status(404).json({ 
        success: false,
        message: '订单不存在'
      });
    }

    // 查询订单项
    const [orderItems] = await connection.execute(`
      SELECT * FROM order_items WHERE order_id = ?
    `, [order_id]);

    // 使用安全的 JSON 解析处理规格字段
    const processedItems = orderItems.map(item => ({
      ...item,
      specifications: safeJSONParse(item.specifications)
    }));

    const orderWithItems = {
      ...orders[0],
      items: processedItems
    };

    res.json({
      success: true,
      message: '获取订单详情成功',
      data: orderWithItems
    });

  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({ 
      success: false,
      message: '获取订单详情失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
};

// 更新订单状态（使用 mysql2）
exports.updateOrderStatus = async (req, res) => {
  let connection;
  try {
    const { order_id } = req.params;
    const { status } = req.body;

    console.log('🔍 更新订单状态，订单ID:', order_id, '状态:', status);

    // 验证状态值
    const validStatuses = ['pending', 'paid', 'preparing', 'ready', 'completed', 'cancelled'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({ 
        success: false,
        message: '无效的订单状态' 
      });
    }

    connection = await pool.getConnection();

    // 更新订单状态
    const [result] = await connection.execute(`
      UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?
    `, [status, order_id]);

    if (result.affectedRows === 0) {
      return res.status(404).json({ 
        success: false,
        message: '订单不存在' 
      });
    }

    // 查询更新后的订单
    const [orders] = await connection.execute(`
      SELECT * FROM orders WHERE id = ?
    `, [order_id]);

    res.json({
      success: true,
      message: '订单状态更新成功',
      data: orders[0]
    });

  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({ 
      success: false,
      message: '更新订单状态失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
};
// 订单支付接口（使用 mysql2）
exports.payOrder = async (req, res) => {
  let connection;
  try {
    console.log('🔍 订单支付请求开始');
    
    // 验证用户认证
    if (!req.user || !req.user.id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证，请重新登录'
      });
    }

    const user_id = req.user.id;
    const { order_id } = req.params;
    const { pay_type = 'wechat' } = req.body;

    console.log('🔍 支付参数:', { user_id, order_id, pay_type });

    // 验证订单ID
    if (!order_id) {
      return res.status(400).json({
        success: false,
        message: '订单ID不能为空'
      });
    }

    connection = await pool.getConnection();
    await connection.beginTransaction();

    // 1. 查询订单信息并验证
    const [orders] = await connection.execute(`
      SELECT * FROM orders 
      WHERE id = ? AND user_id = ?
    `, [order_id, user_id]);

    if (orders.length === 0) {
      await connection.rollback();
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权访问此订单'
      });
    }

    const order = orders[0];
    console.log('🔍 当前订单状态:', order.status);

    // 2. 检查订单状态是否允许支付
    if (order.status !== 'pending') {
      await connection.rollback();
      
      let message = '';
      switch (order.status) {
        case 'paid':
          message = '订单已支付，请勿重复支付';
          break;
        case 'cancelled':
          message = '订单已取消，无法支付';
          break;
        case 'completed':
          message = '订单已完成，无法支付';
          break;
        default:
          message = `订单当前状态为${order.status}，无法支付`;
      }
      
      return res.status(400).json({
        success: false,
        message
      });
    }

    // 3. 更新订单状态为已支付
    const now = new Date();
    const updateSql = `
      UPDATE orders 
      SET status = 'paid', 
          pay_type = ?, 
          pay_time = ?,
          updated_at = NOW()
      WHERE id = ? AND user_id = ?
    `;

    const [updateResult] = await connection.execute(updateSql, [
      pay_type,
      now,
      order_id,
      user_id
    ]);

    if (updateResult.affectedRows === 0) {
      await connection.rollback();
      return res.status(500).json({
        success: false,
        message: '订单状态更新失败'
      });
    }

    // 4. 查询更新后的订单信息
    const [updatedOrders] = await connection.execute(`
      SELECT * FROM orders WHERE id = ?
    `, [order_id]);

    await connection.commit();

    console.log('✅ 订单支付成功，订单ID:', order_id);

    // 返回支付成功信息
    res.json({
      success: true,
      message: '支付成功',
      data: {
        id: updatedOrders[0].id,
        order_no: updatedOrders[0].order_no,
        status: updatedOrders[0].status,
        pay_time: updatedOrders[0].pay_time,
        pay_type: updatedOrders[0].pay_type
      }
    });

  } catch (error) {
    if (connection) await connection.rollback();
    console.error('❌ 订单支付失败:', error);
    res.status(500).json({
      success: false,
      message: '支付失败，服务器错误',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  } finally {
    if (connection) connection.release();
  }
};